package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

@Slf4j
@Configuration
public class TokenUtil {

    private static final long EXPIRE_TIME = 30*60*1000;
    private static final String secretString="dVnsmy+SIX6pNptQdeclDSJ26EMSPEIhvZYKBTTug4k=";
    private static final SecretKey KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

   public static String generateToken(Map<String,Object> map) {
       String token = Jwts.builder()
               .setClaims(map)
               .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME))
               .signWith(KEY).compact();
       return token;

    }

    public static Claims parseJWT(String jwt){   //解析token
        if (!StringUtils.hasLength(jwt)){
            return null;
        }
//创建解析器, 设置签名密钥
        JwtParserBuilder jwtParserBuilder =
                Jwts.parserBuilder().setSigningKey(KEY);

        Claims claims=null;
        try {
//解析token
       claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e){
//签名验证失败
            log.error("解析令牌错误,jwt:{}",jwt);
            return null;
        }finally {
            return claims;
        }

    }
}
